#include <i2c.hpp>

#if defined(CONFIG_TAR4ESP32)
#define SCL_IO_PIN		 16
#define SDA_IO_PIN		 15
#define MASTER_FREQUENCY 400000
#define PORT_NUMBER		 I2C_NUM_0
#endif

I2C::I2C(uint16_t devAddr)
{
#if defined(CONFIG_TAR4ESP32)
	memset(&i2c_bus_config, 0, sizeof(i2c_master_bus_config_t));
	memset(&i2c_dev_conf, 0, sizeof(i2c_device_config_t));

	i2c_bus_config.clk_source					= I2C_CLK_SRC_DEFAULT;
	i2c_bus_config.i2c_port						= PORT_NUMBER;
	i2c_bus_config.scl_io_num					= (gpio_num_t)SCL_IO_PIN;
	i2c_bus_config.sda_io_num					= (gpio_num_t)SDA_IO_PIN;
	i2c_bus_config.glitch_ignore_cnt			= 7;
	i2c_bus_config.flags.enable_internal_pullup = true;

	i2c_dev_conf.dev_addr_length		 = I2C_ADDR_BIT_LEN_7;
	i2c_dev_conf.device_address			 = devAddr;
	i2c_dev_conf.scl_speed_hz			 = MASTER_FREQUENCY;
	i2c_dev_conf.flags.disable_ack_check = true;

	esp_err_t ret = i2c_new_master_bus(&i2c_bus_config, &bus_handle);
	if (ret != ESP_OK)
	{
		LOG("i2c new master bus error.\n");
		return;
	}

	ret = i2c_master_bus_add_device(bus_handle, &i2c_dev_conf, &dev_handle);
	if (ret != ESP_OK)
	{
		LOG("i2c add device error.\n");
		return;
	}
#endif
	LOG("i2c init OK.\n");
}

I2C::~I2C()
{
}

int I2C::Write(uint8_t* data, uint16_t len)
{
#if defined(CONFIG_TAR4ESP32)
	esp_err_t ret = i2c_master_transmit(dev_handle, data, len, 1000);
	if (ret != ESP_OK)
	{
		LOG("i2c write error.\n");
		return -1;
	}
#endif
	return 0;
}

int I2C::Read(uint8_t* txdata, uint16_t txlen, uint8_t* rxdata, uint16_t rxlen)
{
#if defined(CONFIG_TAR4ESP32)
	esp_err_t ret = i2c_master_transmit_receive(dev_handle, txdata, txlen, rxdata, rxlen, 1000);
	if (ret != ESP_OK)
	{
		LOG("i2c read error.\n");
		return -1;
	}
#endif
	return 0;
}